package com.example.musicplayer;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MusicActivity extends AppCompatActivity implements View.OnClickListener {

    //进度条
    private static SeekBar sb;
    private static TextView tv_progress, tv_total, name_song;
    //动画
    private ObjectAnimator animator;
    private MusicService.MusicControl musicControl;
    private String name;
    private Intent intent1, intent2;
    private MyServiceConn conn;
    private boolean isUnBind = false;
    private ImageView ivMusic;


    private Button btnPlay;
    private Button btnPause;
    private Button btnContinuePlay;
    private Button btnExit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        intent1 = getIntent();//获取从Frag1传来的信息
        initView();
    }

    private void initView() {
        ivMusic = (ImageView) findViewById(R.id.iv_music);
        name_song = (TextView) findViewById(R.id.song_name);
        sb = (SeekBar) findViewById(R.id.sb);
        tv_progress = (TextView) findViewById(R.id.tv_progress);
        tv_total = (TextView) findViewById(R.id.tv_total);
        btnPlay = (Button) findViewById(R.id.btn_play);
        btnPause = (Button) findViewById(R.id.btn_pause);
        btnContinuePlay = (Button) findViewById(R.id.btn_continue_play);
        btnExit = (Button) findViewById(R.id.btn_exit);

        btnPlay.setOnClickListener(this::onClick);
        btnPause.setOnClickListener(this::onClick);
        btnContinuePlay.setOnClickListener(this::onClick);
        btnExit.setOnClickListener(this::onClick);

        name = intent1.getStringExtra("name");
        name_song.setText(name);
        //创建一个意图对象，从当前的Activity跳转到Service
        intent2 = new Intent(this, MusicService.class);
        //创建服务链接对象
        conn = new MyServiceConn();
        bindService(intent2, conn, BIND_AUTO_CREATE);//绑定服务
        //为滑动条添加事件监听
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                //当滑动条在末端时，结束动画
                if (progress == seekBar.getMax()) {
                    animator.pause();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            //当滑动条停止调用
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //改变音乐播放进度
                int progress = seekBar.getProgress();
                musicControl.seekTo(progress);
            }
        });

        String position = intent1.getStringExtra("position");
        int i = Integer.parseInt(position);
        ivMusic.setImageResource(Frag1.icons[i]);
        animator = ObjectAnimator.ofFloat(ivMusic, "rotation", 0f, 360.0f);
        animator.setDuration(10000);
        animator.setInterpolator(new LinearInterpolator());
        animator.setRepeatCount(-1);//无线循环
    }

    public static Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle = msg.getData();//获取从子线程发送的音乐播放进度
            //获取当前进度和总时长
            int duration = bundle.getInt("duration");
            int currentPosition = bundle.getInt("currentPosition");
            //对进度条进行设置
            sb.setMax(duration);
            sb.setProgress(currentPosition);
            //歌曲是多少分钟多少秒钟
            int minute = duration / 1000 / 60;
            int second = duration / 1000 % 60;
            String strMinute = null;
            String strSecond = null;
            if (minute < 10) {//如果歌曲时长分钟小于10
                strMinute = "0" + minute;//在分钟前加0
            } else {
                strMinute = minute + "";
            }
            if (second < 10) {//如果歌曲时长秒钟小于10
                strSecond = "0" + second;//在秒钟前加0
            } else {
                strSecond = second + "";
            }
            //显示歌曲当前播放时长
            tv_total.setText(strMinute+":"+strSecond);

             minute = currentPosition / 1000 / 60;
             second = currentPosition / 1000 % 60;
            if (minute < 10) {//如果歌曲时长分钟小于10
                strMinute = "0" + minute;//在分钟前加0
            } else {
                strMinute = minute + "";
            }
            if (second < 10) {//如果歌曲时长秒钟小于10
                strSecond = "0" + second;//在秒钟前加0
            } else {
                strSecond = second + "";
            }
            //显示歌曲总时长
            tv_progress.setText(strMinute+":"+strSecond);
        }
    };

    //连接服务
    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            musicControl = (MusicService.MusicControl) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }

    //判断服务是否被解绑
    private void unBind(boolean isUnBind) {
        //解绑
        if (!isUnBind) {
            musicControl.pausePlay();//暂停播放
            unbindService(conn);//解绑服务
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_play:
                String position = intent1.getStringExtra("position");
                int i = Integer.parseInt(position);
                musicControl.play(i);
                animator.start();
                break;
            case R.id.btn_pause:
                musicControl.pausePlay();
                animator.pause();
                break;
            case R.id.btn_continue_play:
                musicControl.continuePlay();
                animator.start();
                break;
            case R.id.btn_exit:
                unBind(isUnBind);
                isUnBind = true;
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unBind(isUnBind);
    }
}